[jQuery] JS inside the template

Posted by Martin Trigaux on Stack Overflow See other posts from Stack Overflow or by Martin Trigaux
Published on 2010-05-26T10:05:34Z Indexed on 2010/05/26 10:51 UTC
Read the original article Hit count: 212

Hello,

I'm trying to include some javascript code inside a template.

The code of my html page :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 
       "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    <script type="text/javascript" src="jquery-1.4.2.min.js"></script>
    <script type="text/javascript" src="jquery-jtemplates.js"></script>
</head>

<body>
    <div id="infos"></div>
    <div id="my_template"></div>

    <script type="text/javascript">
        $(document).ready(function() {
            $('#my_template').setTemplateURL("my_template.html");
            try {
                $('#my_template').processTemplate({'var' : 1});
            }
            catch (e) {
                $('#infos').html('error : '+e);
            }
            $('#my_button').click(function(){
                alert('it works outside');
            });
        });
    </script>

</body>
</html>

and the template

content of the template<br/>
{#if $T.var == 1}

 <script type="text/javascript">
  $(document).ready(function() {

   $('#my_button').click(function(){
    alert('it works inside');
   });

  });
 </script>
 <input type='submit' id='my_button' value='click me' onclick='alert("direct");'/>

{#else}
 not working
{#/if}

produce me an error inside the infos balise

error : SyntaxError: missing } after function body

if I just put alert('it works inside'); inside the script balise (remove all the jquery related code), the page load, the two message "direct" and "it works outside" are showed but not "it works inside" message.

It's suppose to works as said on the doc page

Allow to use JavaScript code in templates

Thank you

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery